package com.example.main.fragment

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.provider.Settings
import android.view.View
import android.view.WindowInsets
import android.view.WindowManager
import androidx.core.app.NotificationCompat
import com.example.main.R
import com.example.main.databinding.FragmentMessageBinding
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import android.widget.Toast
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat.getSystemService
import com.example.lib_base.mvvm.BaseViewFragment
import android.view.WindowInsetsController

class MessageFragment : BaseViewFragment<FragmentMessageBinding>() {

    companion object {
        private const val CHANNEL_ID = "msg_channel"
        private const val NOTIFICATION_ID = 1001
        private const val PREFS_NAME = "msg_prefs"
        private const val KEY_NOTIFICATIONS = "notifications_enabled"
        private const val KEY_SOUND = "sound_enabled"
        private const val KEY_VIBRATION = "vibration_enabled"
    }

    private var notificationsEnabled = true
    private var soundEnabled = true
    private var vibrationEnabled = true

    override fun initView() {
        loadSettings()
        // 接收通知开关
        biding.switchReceive.setOnCheckedChangeListener { _, isChecked ->
            notificationsEnabled = isChecked
            saveSettings()
            updateSwitchesState()
            val msg = if (isChecked) "已开启接收通知" else "已关闭接收通知"
            Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
        }
        // 声音提醒开关
        biding.switchSound.setOnCheckedChangeListener { _, isChecked ->
            soundEnabled = isChecked
            saveSettings()
            val msg = if (isChecked) "已开启声音提醒" else "已关闭声音提醒"
            Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
        }
        // 震动提醒开关
        biding.switchVibrate.setOnCheckedChangeListener { _, isChecked ->
            vibrationEnabled = isChecked
            saveSettings()
            val msg = if (isChecked) "已开启震动提醒" else "已关闭震动提醒"
            Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
        }

    }


    // 沉浸式状态栏（透明/全屏）
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 沉浸式状态栏（透明/全屏）
        activity?.window?.let { window ->
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                window.setDecorFitsSystemWindows(false)
                window.insetsController?.apply {
                    hide(WindowInsets.Type.statusBars())
                    systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
                }
            } else {
                @Suppress("DEPRECATION")
                window.setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN
                )
            }
        }
        // 夜间模式开关，切换时全局生效
        biding.switchNight.isChecked = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES
        biding.switchNight.setOnCheckedChangeListener { _, isChecked ->
            AppCompatDelegate.setDefaultNightMode(
                if (isChecked){
                    AppCompatDelegate.MODE_NIGHT_YES
                } else {
                    AppCompatDelegate.MODE_NIGHT_NO
                }
            )
            requireActivity().recreate() // 立即刷新主题

        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "消息通知"
            val description = "App消息通知渠道"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                this.description = description
            }
            val notificationManager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun sendTestNotification() {
        if (!notificationsEnabled) {
            Toast.makeText(requireContext(), "通知已关闭", Toast.LENGTH_SHORT).show()
            return
        }
        val builder = NotificationCompat.Builder(requireContext(), CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("测试通知")
            .setContentText("这是一条测试通知")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
        // 设置声音
        if (soundEnabled) {
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            builder.setSound(soundUri)
        }
        // 设置震动
        if (vibrationEnabled) {
            val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                val vibratorManager = requireContext().getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
                vibratorManager.defaultVibrator
            } else {
                @Suppress("DEPRECATION")
                requireContext().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
            }
            vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE))
            builder.setVibrate(longArrayOf(0, 500))
        }
        val notificationManager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(NOTIFICATION_ID, builder.build())
    }

    private fun loadSettings() {
        val prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        notificationsEnabled = prefs.getBoolean(KEY_NOTIFICATIONS, true)
        soundEnabled = prefs.getBoolean(KEY_SOUND, true)
        vibrationEnabled = prefs.getBoolean(KEY_VIBRATION, true)
        biding.switchReceive.isChecked = notificationsEnabled
        biding.switchSound.isChecked = soundEnabled
        biding.switchVibrate.isChecked = vibrationEnabled
        updateSwitchesState()
    }

    private fun saveSettings() {
        val prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        with(prefs.edit()) {
            putBoolean(KEY_NOTIFICATIONS, notificationsEnabled)
            putBoolean(KEY_SOUND, soundEnabled)
            putBoolean(KEY_VIBRATION, vibrationEnabled)
            apply()
        }
    }

    private fun updateSwitchesState() {
        biding.switchSound.isEnabled = notificationsEnabled
        biding.switchVibrate.isEnabled = notificationsEnabled
    }

    override fun initData() {
        // 可在此加载数据
    }
    
}